package com.wyclabs.commons.entity;

import com.alibaba.fastjson.JSON;
import com.wyclabs.commons.constants.BaseResponseCode;
import com.wyclabs.commons.constants.ErrorCodes;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * 基础api返回格式
 * @author rs
 * @date 2019/10/11
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class JsonResult<T> extends BaseResult implements Serializable {

    @ApiModelProperty("结果数据")
    private T data;

    public JsonResult() {
    }

    public JsonResult(T result) {
        data = result;
    }

    public static <T> JsonResult<T> success() {
        return success(null);
    }

    public static <T> JsonResult<T> success(T t) {
        return success(t, ErrorCodes.OK.getDescription());
    }

    public static <T> JsonResult<T> success(T t, String msg) {
        JsonResult<T> result = new JsonResult<>();
        result.setData(t);
        result.setCode(ErrorCodes.OK.getCode());
        result.setMsg(msg);
        return result;
    }

    public static <T> JsonResult<T> error(String code, String description) {
        return error(code, description, null);
    }

    public static <T> JsonResult<T> error(ErrorCodes responseCode) {
        JsonResult<T> result = new JsonResult<>(null);
        result.setCode(responseCode.getCode());
        result.setMsg(responseCode.getDescription());
        result.setData(null);
        return result;
    }

    public static <T extends BaseResponseCode> JsonResult<T> error(T responseCode) {
        JsonResult<T> result = new JsonResult<>(null);
        result.setCode(responseCode.getCode());
        result.setMsg(responseCode.getDescription());
        result.setData(null);
        return result;
    }

    public static <T> JsonResult<T> error(String code, String description, T res) {
        JsonResult<T> result = new JsonResult<>(null);
        result.setCode(code);
        result.setMsg(description);
        result.setData(res);
        return result;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    /**
     * 系统服务间调用使用此方法直接获取result，如果有错误则会直接抛出ModnimSystemApiException
     * @return T
     */
    public T checkThrow() {
        //TODO 异常处理
//        if (!checkSuccess()) {
//            throw new ModnimSystemApiException(this);
//        } else {
//            return data;
//        }
        return data;
    }

}
